package com.shyroke.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.shyroke.common.CommonUtils;
import com.shyroke.entity.Article;
import com.shyroke.entity.ArticlePingLun;
import com.shyroke.entity.Label;
import com.shyroke.entity.SpiderDataDto;
import com.shyroke.entity.User;
import com.shyroke.entity.XiangCe;
import com.shyroke.entity.XiaoShuo;
import com.shyroke.entity.XiaoShuoBean;
import com.shyroke.entity.XiaoShuoEnum;
import com.shyroke.service.ArticlePingLunServiceI;
import com.shyroke.service.ArticleServiceI;
import com.shyroke.service.DaiShenHeServiceI;
import com.shyroke.service.LabelServiceI;
import com.shyroke.service.UserServiceI;
import com.shyroke.service.XiangCeServiceI;
import com.shyroke.service.XiaoShuoServiceI;

@Controller
@RequestMapping(value="/guancangAction")
public class GuanCangAction {

	@Autowired
	private ArticleServiceI articleService;
	@Autowired
	private LabelServiceI labelService;
	
	@Autowired
	private XiangCeServiceI xiangceService;
	
	@Autowired
	private DaiShenHeServiceI daishenheService;
	
	@Autowired
	private UserServiceI userService;
	
	@Autowired
	private ArticlePingLunServiceI articlePingLunService;
	
	@Autowired
	private ServletContext context;
	
	@Autowired
	private XiaoShuoServiceI xiaoshuoService;
	
	/**
	 * 跳转到馆藏页面
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/guancangView")
	public ModelAndView guancangView(ModelAndView model, HttpSession session,
			@RequestParam(value = "wenjianjia", required = false) String wenjianjia,
			@RequestParam(value = "userId", required = false) Integer userId) throws IOException {
		User user = null;
		List<Article> articleList=null;
		if(userId!=null && userId!=0) {
			model.addObject("userId", userId);  //设置为别的用户访问的标记
			//说明是查看别的用户的信息,且只能查看公开的文章
			user=userService.selectByUserId(userId);
			
			if(wenjianjia!=null && !wenjianjia.equals("") && !wenjianjia.equals("馆藏") &&!wenjianjia.contains(".txt")) {
				//用户选择查看某个文件夹的文章
				articleList=articleService.selctAllByPublicWenjianjia(user.getId(),wenjianjia);
			}else if(wenjianjia!=null && !wenjianjia.equals("") && wenjianjia.contains(".txt")) {
				//查看小说
				XiaoShuo xiaoshuo = xiaoshuoService.selectByUserIdAndFileName(user.getId(),wenjianjia);
				model.addObject("xiaoshuo", xiaoshuo);
				model.setViewName("xiaoshuo/show");
				//该值用于表示这是其他用户访问的小说
				model.addObject("otherMaker", "otherMaker");
				model.addObject("otherUserId", userId);
				return model;
			}
			else {
				//查看所有文章
				articleList=articleService.selectAllPublic(user.getId());
			}
			
		}else {
			
				 user=(User)session.getAttribute("user");
				 
					if(wenjianjia!=null && !wenjianjia.equals("") && !wenjianjia.equals("馆藏") && !wenjianjia.contains(".txt")) {
						//用户选择查看某个文件夹的文章
						articleList=articleService.selctAllByWenjianjia(user.getId(),wenjianjia);
					}else if(wenjianjia!=null && !wenjianjia.equals("") && wenjianjia.contains(".txt")) {
						//查看小说
						XiaoShuo xiaoshuo = xiaoshuoService.selectByUserIdAndFileName(user.getId(),wenjianjia);
						model.addObject("xiaoshuo", xiaoshuo);
						model.setViewName("xiaoshuo/show");
						
						return model;
					}
					else {
						//查看所有文章
						articleList=articleService.selectAll(user.getId());
					}
			
			
		}
		
		
		model.addObject("articleList", articleList);
		model.setViewName("user/guancang");
		
		return model;
		
	}
	
	/**
	 * 跳转到新增文章的页面
	 */
	@RequestMapping(value="/addArticleView")
	public String addArticleView() {
		
		return "article/add";
	}
	
	
	/**
	 * 获取某个用户的馆藏关键字返回json格式字符串
	 * @return
	 */
	@RequestMapping(value="getKey")
	@ResponseBody
	public List<Map<String,Object>> getKey(HttpSession session) {
		User user=(User)session.getAttribute("user");
		List<Map<String,Object>> dataList=new ArrayList<Map<String,Object>>();
		
		Map<String,Object> dataMap=null;
		
		List<Article> articleList=articleService.selectAll(user.getId());
		List<String> keyList=new ArrayList<String>();
		for(Article article:articleList) {
			
			if(!keyList.contains(article.getKey())) {
				// 重复的key不再添加
				keyList.add(article.getKey());
			}
		}
		
		for(String key:keyList) {
			dataMap=new HashMap<String,Object>();
			dataMap.put("keyValue", key);
			dataMap.put("keyText", key);
			dataList.add(dataMap);
		}
		
		return dataList;
	}

	/**
	 * 获取新增文章页面所需的文件夹树形结构的数据
	 * @return
	 */
	@RequestMapping(value="getFileTreeData")
	@ResponseBody
	public List<Map<String,Object>> getFileTreeData(HttpSession session){
		User user=(User)session.getAttribute("user");
		
		List<Map<String,Object>> dataList=new ArrayList<Map<String,Object>>();
		
		Map<String,Object> dataMap= null;
		 
		List<Article> articleList=articleService.selectAll(user.getId());
		List<String> fileList=new ArrayList<String>();
		for(Article article:articleList) {
			
			if(!fileList.contains(article.getWenjianjia())) {
				// 重复的文件夹不再添加
				fileList.add(article.getWenjianjia());
			}
		}
		
//		for(String wenjianjia:fileList) {
		for(int i=0;i<fileList.size();i++) {
			dataMap=new HashMap<String,Object>();
			dataMap.put("text", fileList.get(i));
			if(i==0) {
				dataMap.put("state", "checked");
			}
			
			dataList.add(dataMap);
		}
		dataMap=new HashMap<>();
		dataMap.put("text", "点击新增文件夹");
		dataList.add(dataMap);
		
		return dataList;
	}
	
	
	/**
	 * 获取标签的数据
	 * @return
	 */
	@RequestMapping(value="/getLabel")
	@ResponseBody
	public List<Map<String,Object>> getLabel(){
		List<Map<String,Object>> dataList=new ArrayList<Map<String,Object>>();
		
		List<Label> labelList=labelService.selectAll();
		Map<String,Object> dataMap = null;
		for(Label label:labelList) {
			dataMap = new HashMap<String,Object>();
			dataMap.put("keyValue", label.getName());
			dataMap.put("keyText", label.getName());
			dataList.add(dataMap);
		}
		
		return dataList;
	}
	
	/**
	 * 保存文章
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="saveAdd")
	@ResponseBody
	public Map<String,Object> saveAdd(Article article,HttpSession session) throws IOException {
		
		Map<String,Object> map=new HashMap<String,Object>();
		
	
		
		articleService.insert(article,session);
		
		map.put("msg", "保存成功");
		
		return map;
	}
	
	
	/**
	 * 跳转到添加音乐的页面
	 * @return
	 */
	@RequestMapping(value="addxiangceView")
	public String addMusicView() {
		
		return "xiangce/add";
	}
	
	
	@RequestMapping(value="/saveAddxiangce")
	@ResponseBody
	public Map<String,Object> saveAddxiangce(HttpSession session,XiangCe xiangce) throws IOException{
		Map<String,Object> map=new HashMap<String,Object>();
		
		xiangceService.insert(session,xiangce);
		
		map.put("msg", "保存成功");
		return map;
	}
	
	/**
	 * 用户推荐文章到首页
	 * @param articleId
	 * @return
	 */
	@RequestMapping(value="/tuijian")
	@ResponseBody
	public Map<String,Object> tuijian(@RequestParam(value="articleId",required=true)Integer articleId){
		
		Map<String,Object> map=new HashMap<String,Object>();
		
		Article article=articleService.selectById(articleId);
		boolean articleIsExist=daishenheService.isExist(articleId);
		boolean yuanchuang=articleService.isYuanChuang(articleId); //判断是否原创文章
		if(article.getIsshow()=="是") {
			//表示已经在首页展示
			map.put("errMsg", "该文章已经在首页展示");
		}else if(article.getQuanxian().equals("私密")) {
			//私密文章不允许展示到首页
			map.put("errMsg", "私密文章不允许展示到首页");
		}else if(articleIsExist) {
			//不可重复推荐
			map.put("errMsg", "不可重复推荐");
		}else if(!yuanchuang) {
			//非原创文章不能推荐
			map.put("errMsg", "必须得是原创的文章才能推荐");
		}else {
			daishenheService.insert(articleId);
		}
		
		return map;
	}
	
	
	/**
	 * 删除文章
	 * @param articleId
	 * @return
	 */
	@RequestMapping(value="/del")
	@ResponseBody
	public Map<String,Object> del(@RequestParam(value="articleId",required=true)Integer articleId){
		
		Map<String,Object> map=new HashMap<String,Object>();
		
	    articleService.delById(articleId);
		
		
		return map;
	}
	
	/**
	 * 跳转到文章详细页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/articleDescView")
	public ModelAndView articleDescView(ModelAndView model,@RequestParam(value="articleId",required=true)Integer articleId,HttpSession session){
		Article article=articleService.selectById(articleId);
		
		if(article.getAuthor().equals("站外")) {
			//该文章来自站外
			List<SpiderDataDto> dataDtos = (List)session.getAttribute("spiderDataDtos");
			dataDtos.stream().filter(p->p.getTitle().equals(article.getTitle()));
			model.addObject("url", dataDtos.get(0).getUrl());
			model.setViewName("article/other_show");
			return model;
		}
		
		articleService.addMount("阅读",articleId);
		List<ArticlePingLun> pinglunList=articlePingLunService.selectByArticleId(articleId);
		model.addObject("pinglunList", pinglunList);
		model.addObject("article", article);
		model.setViewName("article/desc");
		return model;
	}
	
	/**
	 * 保存用户转载的文章
	 * @return
	 */
	@RequestMapping(value="saveShoucang")
	@ResponseBody
	public Map<String,Object> saveShoucang(Article article,HttpSession session){
		Map<String,Object> map=new HashMap<String,Object>();
		
		articleService.shoucang(article, session);
		map.put("msg", "收藏成功");
		
		return map;
	}
	
	/**
	 * 判断该用户是否有收藏权限，
	 * 没有权限的：1.未登录的用户  2.该用户已经有该文章
	 * @return
	 */
	@RequestMapping(value="/isshoucangquanxian")
	@ResponseBody
	public Map<String,Object> isshoucangquanxian(HttpSession session,@RequestParam(value="articleId",required=true)Integer articleId){
		Map<String,Object> map=new HashMap<String,Object>();
		User user=(User)session.getAttribute("user");
		Article article=articleService.selectById(articleId);
		
		if(user==null) {
			//说明用户未登录
			map.put("errMsg", "请先登录");
		}else if(article.getUserid()==user.getId()) {
			//说明该文章的拥有者和该用户是同一个人，不能收藏自己的文章
			map.put("errMsg", "不能收藏自己的文章");
		}else {
			//可以正常收藏文章
			map.put("msg", "可以正常收藏文章");
		}
		
		
		return map;
	}
	
	/**
	 * 跳转到修改文章的页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/uptView")
	public ModelAndView uptView(ModelAndView model,@RequestParam(value="articleId",required=true)Integer articleId) {
		Article article=articleService.selectById(articleId);
		
		model.addObject("article", article);
		model.setViewName("article/upt");
		return model;
	}
	
	
	/**
	 * 保存修改后的文章
	 * @return
	 */
	@RequestMapping(value="/saveupt")
	@ResponseBody
	public Map<String,Object> saveupt(HttpSession session,Article article){
		Map<String,Object> map=new HashMap<String,Object>();
		
		
		articleService.uptArticle(article);
		
		map.put("msg", "修改成功");
		return map;
	}
	
	
	/**
	 * 获取文件夹树形结构所需的数据
	 * @return
	 */
	@RequestMapping(value="/getwenjianjiaData")
	@ResponseBody
	public List<Map<String,Object>> getwenjianjiaData(HttpSession session,@RequestParam(value="userId",required=false)Integer userId){
		List<Map<String,Object>> dataList=new ArrayList<Map<String,Object>>();
		
		List<Map<String,Object>> chirldList=new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> xiaoshuoChildList=new ArrayList<Map<String,Object>>();
		User user= null ;
		List<String> wenjianjiaList1= null;
		List<String> xiaoshuoList  = null;
		if(userId!=null) {
			//说明访问别人的馆藏
			user=userService.selectByUserId(userId);
			wenjianjiaList1=articleService.selectWenjianjiaByUserIdPublic(user.getId());  
			xiaoshuoList  = xiaoshuoService.getAllXiaoshuoByUserId(user.getId(),context,XiaoShuoEnum.SHOW_PUBLIC);
		}else {
			//访问自己的馆藏
			user=(User)session.getAttribute("user");
			wenjianjiaList1=articleService.selectWenjianjiaByUserId(user.getId());  
			xiaoshuoList  = xiaoshuoService.getAllXiaoshuoByUserId(user.getId(),context,XiaoShuoEnum.SHOW_ALL);
		}
		
		List<String> wenjianjiaList=CommonUtils.getNoRepetition(wenjianjiaList1);
		Map<String,Object> columnMap=null;
		for(int i=0;i<wenjianjiaList.size();i++) {
			columnMap=new HashMap<String,Object>();
			
			columnMap.put("id", "11"+(i+1));
			columnMap.put("text", wenjianjiaList.get(i));
			chirldList.add(columnMap);
		}
		
		for(int i=0;i<xiaoshuoList.size();i++) {
			columnMap=new HashMap<String,Object>();
			columnMap.put("id", "12"+(i+1));
			columnMap.put("text", xiaoshuoList.get(i));
			xiaoshuoChildList.add(columnMap);
		}
		
		List<Map<String,Object>>  childFolder=new ArrayList<Map<String,Object>>();
		
		//短篇文章的父文件夹
		Map<String,Object> duanMap = new HashMap<>();
		duanMap.put("id", 11);
		duanMap.put("text", "文章");
		duanMap.put("children", chirldList);
		childFolder.add(duanMap);
		
		//长篇文章的父文件夹
		Map<String,Object> changMap = new HashMap<>();
		changMap.put("id", 12);
		changMap.put("text", "小说");
		changMap.put("children", xiaoshuoChildList);
		childFolder.add(changMap);
		
		Map<String,Object> parentMap=new HashMap<String,Object>();
		parentMap.put("id", 1);
		parentMap.put("text", "馆藏");
		parentMap.put("state", "open");
		parentMap.put("children", childFolder);
		dataList.add(parentMap);
		return dataList;
	}
	
	/**
	 * 跳转到新增小数的页面
	 * @return
	 */
	@RequestMapping(value="addxiaoshuoView")
	public String addxiaoshuoView() {
		
	return "xiaoshuo/add";	
	}
	
	/**
	 * 保存新增的小说
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value="saveAddxiaoshuo")
	public String saveAddxiaoshuo(@RequestParam(value="quanxian")String quanxian,@RequestParam(value="title")String title,@RequestParam(value="xiaoshuo")MultipartFile file,
			HttpSession sesion) throws IllegalStateException, IOException{
		Map<String,Object> resultMap = new HashMap<>();
		User user =(User)sesion.getAttribute("user");
		String originName = file.getOriginalFilename();
		
		if(!CommonUtils.isTxtFile(originName)) {
			//不是TXT文件
			resultMap.put("errMsg", "只能是txt文件");
			return "xioashuo/saveError";
		}
		
		//创建“xiaoshuo/用户ID”文件夹  
		String uploadDirById  = context.getRealPath("/xiaoshuo/"+user.getId());
		File desFileById = new File(uploadDirById);
		if(!desFileById.exists()) {
			desFileById.mkdirs();
		}
		
		String uploadDir  = context.getRealPath("/xiaoshuo/"+user.getId());
		File desFile = new File(uploadDir+"/"+title+".txt");
		
		XiaoShuo xiaoShuo = new XiaoShuo();
		xiaoShuo.setFilename(title+".txt");
		xiaoShuo.setQuanxian(quanxian);
		xiaoShuo.setUserid(user.getId());
		
		xiaoshuoService.insert(xiaoShuo,file);
		file.transferTo(desFile);
		
		
		
		return "xiaoshuo/addSuccess";
	}
	
}
